import 'dart:async';
import 'package:flutter/material.dart';
import 'websocket_service.dart';
import 'offline_message_service.dart';

/// WebSocket管理器 - 负责应用级别的WebSocket连接管理
class WebSocketManager {
  static final WebSocketManager _instance = WebSocketManager._internal();
  factory WebSocketManager() => _instance;
  WebSocketManager._internal();

  final WebSocketService _wsService = WebSocketService();
  final WebSocketNotificationService _notificationService = WebSocketNotificationService();
  final OfflineMessageService _offlineMessageService = OfflineMessageService();
  
  StreamSubscription? _connectionSubscription;
  StreamSubscription? _messageSubscription;
  
  bool _isInitialized = false;
  String? _currentUserId;

  /// 初始化WebSocket管理器
  Future<void> initialize(BuildContext context) async {
    if (_isInitialized) {
      return;
    }

    try {
      // 初始化离线消息服务
      await _offlineMessageService.initialize();
      
      // 初始化通知服务
      _notificationService.initialize();
      
      // 监听连接状态
      _connectionSubscription = _wsService.connectionStream.listen((isConnected) {
        if (isConnected) {
          _showConnectionStatus(context, '已连接到服务器', isSuccess: true);
          // 连接成功后同步离线消息
          _syncOfflineMessages();
        } else {
          _showConnectionStatus(context, '与服务器断开连接', isSuccess: false);
        }
      });

      // 监听消息
      _messageSubscription = _wsService.messageStream.listen((message) {
        _handleGlobalMessage(context, message);
      });

      _isInitialized = true;
      
    } catch (e) {
    }
  }

  /// 连接WebSocket（用户登录后调用）
  Future<void> connectWithUser(String userId) async {
    if (_currentUserId == userId && _wsService.isConnected) {
      return;
    }

    _currentUserId = userId;
    await _wsService.connect(userId: userId);
  }

  /// 断开WebSocket连接（用户登出时调用）
  Future<void> disconnect() async {
    _currentUserId = null;
    await _wsService.disconnect();
  }

  /// 处理全局消息
  void _handleGlobalMessage(BuildContext context, WebSocketMessage message) {
    final content = message.content;
    final notificationType = content['notificationType'] as String?;
    
    // WebSocket消息是实时消息，不需要保存到Redis（Redis由后端管理）
    // 只显示实时通知给用户
    
    // 根据消息类型显示不同的通知
    switch (notificationType) {
      case 'comment_reply':
        _showNotification(
          context, 
          '评论回复', 
          '${content['senderName'] ?? '有人'}回复了您的评论',
          onTap: () => _navigateToComment(context, content),
        );
        break;
      case 'post_reply':
        _showNotification(
          context, 
          '帖子回复', 
          '${content['senderName'] ?? '有人'}回复了您的帖子',
          onTap: () => _navigateToPost(context, content),
        );
        break;
      case 'like':
        _showNotification(
          context, 
          '获得点赞', 
          '${content['senderName'] ?? '有人'}点赞了您的${content['targetType'] == 'post' ? '帖子' : '评论'}',
        );
        break;
      case 'follow':
        _showNotification(
          context, 
          '新粉丝', 
          '${content['senderName'] ?? '有人'}关注了您',
        );
        break;
    }
    
    // 收到实时消息后，触发消息列表刷新
    _offlineMessageService.syncOfflineMessages();
  }

  /// 显示连接状态
  void _showConnectionStatus(BuildContext context, String message, {required bool isSuccess}) {
    if (!context.mounted) return;
    
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isSuccess ? Colors.green : Colors.red,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  /// 显示通知
  void _showNotification(
    BuildContext context, 
    String title, 
    String message, 
    {VoidCallback? onTap}
  ) {
    if (!context.mounted) return;
    
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
            Text(message),
          ],
        ),
        action: onTap != null ? SnackBarAction(
          label: '查看',
          onPressed: onTap,
        ) : null,
        duration: const Duration(seconds: 4),
      ),
    );
  }

  /// 导航到评论详情
  void _navigateToComment(BuildContext context, Map<String, dynamic> content) {
    final postId = content['postId']?.toString();
    if (postId != null) {
      // 这里需要根据您的路由配置进行导航
      // 例如：context.go('/community/detail/$postId');
    }
  }

  /// 导航到帖子详情
  void _navigateToPost(BuildContext context, Map<String, dynamic> content) {
    final postId = content['postId']?.toString();
    if (postId != null) {
      // 这里需要根据您的路由配置进行导航
      // 例如：context.go('/community/detail/$postId');
    }
  }

  /// 发送评论回复通知
  Future<void> sendCommentReplyNotification({
    required String toUserId,
    required String commentId,
    required String replyContent,
    required String postId,
    required String postTitle,
    String? senderName,
  }) async {
    try {
      await _notificationService.sendCommentReplyNotification(
        toUserId: toUserId,
        commentId: commentId,
        replyContent: replyContent,
        postId: postId,
        postTitle: postTitle,
      );
    } catch (e) {
    }
  }

  /// 发送帖子回复通知
  Future<void> sendPostReplyNotification({
    required String toUserId,
    required String postId,
    required String replyContent,
    required String postTitle,
    String? senderName,
  }) async {
    try {
      await _notificationService.sendPostReplyNotification(
        toUserId: toUserId,
        postId: postId,
        replyContent: replyContent,
        postTitle: postTitle,
      );
    } catch (e) {
    }
  }

  /// 获取WebSocket连接状态
  bool get isConnected => _wsService.isConnected;

  /// 获取连接状态流
  Stream<bool> get connectionStream => _wsService.connectionStream;

  /// 获取消息流
  Stream<WebSocketMessage> get messageStream => _wsService.messageStream;

  /// 获取离线消息服务
  OfflineMessageService get offlineMessageService => _offlineMessageService;

  /// 同步离线消息
  Future<void> _syncOfflineMessages() async {
    try {
      await _offlineMessageService.syncOfflineMessages();
    } catch (e) {
    }
  }

  /// 释放资源
  void dispose() {
    _connectionSubscription?.cancel();
    _messageSubscription?.cancel();
    _notificationService.dispose();
    _offlineMessageService.dispose();
    _wsService.dispose();
    _isInitialized = false;
  }
}